#include "music.h"
#include "ui_music.h"
#include <QTableView>
#include <QStandardItemModel>
#include <QNetworkAccessManager>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QPainter>
#include <QDebug>

music::music(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::music),
    pmodel(new QStandardItemModel(0, 4, this)), // 确保列数设为 4
    manager(new QNetworkAccessManager(this)),
    playlist(new QMediaPlaylist(this)),
    player(new QMediaPlayer(this))


{
    ui->setupUi(this);

    // Set the header labels for the table model
    pmodel->setHorizontalHeaderLabels(QStringList() << "歌曲名" << "专辑" << "歌手" << "时长");
    ui->tableView->setModel(pmodel);

    ui->tableView->setStyleSheet("QTableView { background: transparent; }"
                                  "QHeaderView::section { background: transparent; }"
                                  "QTableCornerButton::section { background: transparent; }"
                                  "QTableView::item { color: white; }");
    ui->tableView->setFrameShape(QFrame::NoFrame);
    ui->tableView->verticalHeader()->setHidden(true); // 隐藏行号
    ui->tableView->horizontalHeader()->setHidden(true); // 隐藏列号
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // 横向栏位伸展

    connect(manager, &QNetworkAccessManager::finished, this, &music::replyFinished);

    player->setPlaylist(playlist);
    connect(player, &QMediaPlayer::positionChanged, this, &music::positionChangedSlot);
    connect(player, &QMediaPlayer::durationChanged, this, &music::durationChangedSlot);
    ui->verticalSlider->setRange(0,100);
    ui->verticalSlider->setValue(50);
    connect(ui->verticalSlider, &QSlider::valueChanged, this, & music::on_verticalSlider_valueChanged);

    lyricTimer = new QTimer(this);
    lyricTimer->setInterval(500); // 歌词滚动间隔，可以根据需要调整
    connect(lyricTimer, &QTimer::timeout, this, &music::scrollLyric);
    ui->lyricLabel = new QLabel(this); // 或者使用ui->lyricLabel;
    ui->lyricLabel->setAlignment(Qt::AlignCenter);
    ui->lyricLabel->setWordWrap(true);
}

music::~music()
{
    delete ui;
    lyricTimer->stop();
    delete lyricTimer;
}

void music::replyFinished(QNetworkReply* reply)
{
    if(reply->error() == QNetworkReply::NoError) {
        qDebug() << "访问服务器成功";
        parseJson(reply->readAll());
    } else {
        qDebug() << "网络错误:" << reply->errorString();
    }
    reply->deleteLater(); // 确保回复被删除
}

void music::parseJson(QByteArray byteArray)
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);
    if (!doc.isObject())
    {
        qDebug() << "错误的JSON文档";
        return;
    }

    QJsonObject obj = doc.object();
    if (!obj.contains("result") || !obj.value("result").isObject())
    {
        qDebug() << "JSON对象没有result或格式不对";
        return;
    }

    QJsonObject resultObj = obj.value("result").toObject();
    if (!resultObj.contains("songs") || !resultObj.value("songs").isArray())
    {
        qDebug() << "JSON对象没有歌曲或格式不对";
        return;
    }

    QJsonArray songsArr = resultObj.value("songs").toArray();
    qDebug() << "一共搜索到" << songsArr.size() << "首歌曲";

    pmodel->setRowCount(songsArr.size()); // 设置行数为歌曲数量

    for (int i = 0; i < songsArr.size(); ++i)
    {
        QJsonObject songObj = songsArr[i].toObject();
        QString songName = songObj.value("name").toString();
        QString albumName = songObj.value("album").toObject().value("name").toString();
        QString singerName;

        QJsonArray artistsArray = songObj.value("artists").toArray();
        for (const auto& artist : artistsArray)
        {
            singerName += artist.toObject().value("name").toString() + " ";
        }

        float duration = songObj.value("duration").toDouble() / 1000.0 / 60.0; // 转为分钟

        qDebug() << "ID:" << songObj.value("id").toDouble() << " 歌曲名:" << songName
                 << " 专辑名:" << albumName << " 歌手名:" << singerName << " 时长:" << duration;

        pmodel->setItem(i, 0, new QStandardItem(songName));
        pmodel->setItem(i, 1, new QStandardItem(albumName));
        pmodel->setItem(i, 2, new QStandardItem(singerName.trimmed())); // 去掉最后一个空格
        pmodel->setItem(i, 3, new QStandardItem(QString::number(duration, 'f', 2))); // 保留两位小数
//        int songId = songObj.value("id").toInt();

    }

    // 添加音乐的播放连接到播放列表
    playlist->clear(); // 清除之前的内容
    for (const auto& song : songsArr)
    {
        QJsonObject songObj = song.toObject();
        unsigned int id = songObj.value("id").toDouble();
        playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
    }

}

void music::getLyric(QByteArray byteArray)
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);
    if(doc.isObject())
    {
        QJsonObject obj1 = doc.object();
        if(obj1.contains("lrc") == false)
        {
            qDebug()<<"错误的json对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("lrc");
        if(var.isObject() == false)
        {
            qDebug()<<"lrc的值不是一个对象"<<endl;
            return;
        }
        QJsonObject lrcobj = var.toObject();\
        if(lrcobj.contains("lyric") == false)
        {
            qDebug()<<"json对象没有歌词"<<endl;
            return;
        }
        var = lrcobj.value("lyric");
        QString lyric = lrcobj.value("lyric").toString();
        qDebug()<<lyric<<endl;
    }

//    QNetworkAccessManager *manager = new QNetworkAccessManager();
//        QObject::connect(manager, &QNetworkAccessManager::finished, this, [this, songId](QNetworkReply *reply) {
//            qDebug() << "获取歌词请求完成，songId: " << songId;

//            if (reply->error()) {
//                qDebug() << "获取歌词失败: " << reply->errorString();
//                reply->deleteLater();
//                return;
//            }

//            QByteArray jsonData = reply->readAll();
//            QJsonDocument doc = QJsonDocument::fromJson(jsonData);
//            QJsonObject obj = doc.object();

//            if (obj.contains("lrc") && obj["lrc"].isObject()) {
//                QJsonObject lrcObj = obj["lrc"].toObject();
//                if (lrcObj.contains("lyric")) {
//                    QString rawLyric = lrcObj["lyric"].toString();
//                    // 处理原始歌词，例如移除时间戳等
//                    lyrics = rawLyric.split('\n'); // 假设每行歌词后有一个换行符
//                    qDebug() << "获取到歌词: " << rawLyric; // 输出原始歌词内容
//                    lyricTimer->start(); // 开始滚动歌词
//                } else {
//                    qDebug() << "歌词对象中没有找到 'lyric' 字段";
//                }
//            } else {
//                qDebug() << "歌词对象中没有找到 'lrc' 字段";
//            }

//            reply->deleteLater();
//        });

//        QString url = QString("https://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(songId);
//            manager->get(QNetworkRequest(QUrl(url)));
//            if (lyrics.isEmpty())
//            {
//                 lyricTimer->start(); // 启动歌词定时器
//             }
}
void music::scrollLyric()
{
    if (!lyrics.isEmpty())
        {
            static int lyricIndex = 0; // 当前歌词索引
            qDebug() << "当前歌词索引: " << lyricIndex; // 输出当前歌词索引
            ui->lyricLabel->setText(lyrics.at(lyricIndex)); // 显示当前行歌词
            lyricIndex = (lyricIndex + 1) % lyrics.size(); // 移动到下一行歌词，如果到达末尾则回到第一行
        } else {
            qDebug() << "歌词列表为空";
        }
}

void music::on_pushButton_clicked()
{
    QString searchQuery = ui->lineEdit->text();
    if (!searchQuery.isEmpty()) {
        QString url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(searchQuery);
        manager->get(QNetworkRequest(QUrl(url)));
    } else {
        qDebug() << "搜索内容不能为空！";
    }
}

void music::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0, 0, width(), height(), QPixmap(":/image/background.jpg"));
}

void music::on_tableView_doubleClicked(const QModelIndex &index)
{
    if (index.isValid())
    {
        playlist->setCurrentIndex(index.row());
        player->play();
    }
}

void music::positionChangedSlot(qint64 position)
{
    ui->horizontalSlider->setValue(position);
}

void music::durationChangedSlot(qint64 duration)
{
    ui->horizontalSlider->setRange(0, duration);
}

void music::on_horizontalSlider_sliderReleased()
{
    qint64 var = ui->horizontalSlider->value();
    player->setPosition(var);
}

void music::on_pushButton_3_clicked() // Play/Pause
{
    if (player->state() == QMediaPlayer::PlayingState) {
        player->pause();
    } else if (player->state() == QMediaPlayer::PausedState) {
        player->play();
    }
}

void music::on_pushButton_2_clicked() // Previous
{
    playlist->previous();
    player->play();
}

void music::on_pushButton_4_clicked() // Next
{
    playlist->next();
    player->play();
}

void music::on_verticalSlider_valueChanged(int value)
{
    // 将音量滑块的值（0-100）转换为QMediaPlayer接受的音量范围（0.0-1.0）
        float volume = value;

        // 设置播放器的音量
        player->setVolume(volume);
}
